package com.shuai.api_platform.service.impl;

import com.shuai.api_platform.service.FileService;
import com.shuai.api_platform.utils.FileUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.nio.file.Files;
import java.time.LocalDateTime;

@Service
@Slf4j
public class FileServiceImpl implements FileService {


    @Value("${annex.storage-path}")
    private String fileSavePath;


    /**
     * 上传文件，主要完成文件的持久化
     */
    @Override
    public String uploadFile(MultipartFile multipartFile) throws IOException {
        File file = new File(fileSavePath);
        if (!file.exists()) {
            if (!file.mkdirs()) {
                throw new IOException("创建文件夹失败！" + fileSavePath);
            }
        }
        String storageName = FileUtils.getStorageName(multipartFile);
        File fileTarget = new File(file, storageName);
        multipartFile.transferTo(fileTarget);
        return storageName;
    }


    /**
     * 下载文件服务，将文件输出到用户响应对象的输出流中
     */
    @Override
    public void downLoadFile(HttpServletResponse response, String fileStorageName) throws IOException {
        File file = new File(fileSavePath + fileStorageName);
        if (!file.exists()) {
            log.error(LocalDateTime.now() + "下载的文件不存在【{}】", fileStorageName);
            throw new IOException("下载的文件不存在");
        }

        InputStream inputStream = null;
        OutputStream outputStream = null;


        try {
            outputStream = response.getOutputStream();
            inputStream = Files.newInputStream(file.toPath());
            byte[] buffer = new byte[1024];
            int length = 0;
            while ((length = inputStream.read(buffer)) != -1) {
                outputStream.write(buffer, 0, length);
            }
            log.info("用户下载了文件：{}", fileStorageName);
        } finally {
            if (inputStream != null) {
                inputStream.close();
            }
            if (outputStream != null) {
                outputStream.close();
            }
        }
    }
}
